﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Documents;
using System.Windows.Xps.Packaging;
using System.Windows.Markup;
using System.Xml;

namespace 合并XPS文件
{
    class XpsMergeTool
    {
        //完全不使用类，函数方式
        public void MergeDocument()
        {

            string fristFile = "test1.xps";
            string secoFile = "test2.xps";

            string newFile = "xpsShow.xps";
            File.Delete(newFile);


            FixedDocumentSequence newFds = new FixedDocumentSequence();//创建一个新的文档结构

            DocumentReference newDocRef = AddPage(fristFile);//加入第一个文件
            newFds.References.Add(newDocRef);

            newDocRef = AddPage(secoFile);
            newFds.References.Add(newDocRef);//加入第二个文件

            //xps写入新文件
            var NewXpsDocument = new XpsDocument(newFile, System.IO.FileAccess.ReadWrite);
            var xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(NewXpsDocument);
            xpsDocumentWriter.Write(newFds);
            NewXpsDocument.Close();

        }

        public static DocumentReference AddPage(string fileName)
        {
            DocumentReference newDocRef = new DocumentReference();
            FixedDocument newFd = new FixedDocument();

            XpsDocument xpsDocument = new XpsDocument(fileName, FileAccess.Read);
            FixedDocumentSequence docSeq = xpsDocument.GetFixedDocumentSequence();

            foreach (DocumentReference docRef in docSeq.References)
            {
                FixedDocument fd = docRef.GetDocument(false);

                foreach (PageContent oldPC in fd.Pages)
                {
                    Uri uSource = oldPC.Source;//读取源地址
                    Uri uBase = (oldPC as IUriContext).BaseUri;//读取目标页面地址

                    PageContent newPageContent = new PageContent();
                    newPageContent.GetPageRoot(false);//这个地方应当是把文档解压成一个包放到内存中我们再去读取
                    newPageContent.Source = uSource;
                    (newPageContent as IUriContext).BaseUri = uBase;
                    newFd.Pages.Add(newPageContent);//将新文档追加到新的documentRefences中
                }
            }
            newDocRef.SetDocument(newFd);
            xpsDocument.Close();
            return newDocRef;
        }
    }
}
